﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Mvc4Learn.Filters
{
    /* string currentRole = GetRole(httpContext.User.Identity.Name);

 if (Roles.Contains(currentRole))
     return true;
 return false;*/
    //            return base.AuthorizeCore(httpContext);

    public class ManagerOnlyAttribute : AuthorizeAttribute
    {
        // 只需重载此方法，模拟自定义的角色授权机制  
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //获得当前的验证cookie
            HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            //如果当前的cookie为空，则返回。
            if (authCookie == null || authCookie.Value == "")
            {
                return false;
            }
            FormsAuthenticationTicket authTicket;
            try
            {
                //对当前的cookie进行解密
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                return false;
            }

            if (authTicket != null)
            {
                //和存入时的分隔符有关系，此处存入时的分隔符为逗号
                var userRoles = authTicket.UserData.Split(new[] {','}).ToList();
                var roles = Roles.Split(new[] {','}).ToList();
//                return roles.All(x => userRoles.Contains(x));
                return roles.Any(x => userRoles.Contains(x));
            }
            return false;

        }

    }
    //            if (httpContext.User != null)
    //            {
    //                //从用户标识和角色名称数组（标识表示的用户属于该数组）初始化 System.Security.Principal.GenericPrincipal 类的新实例。
    //                Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
    //            }
}